<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <link rel="stylesheet" href="./css/bootstrap.min.css" />
  <style>
    .form-select {
      width: 103px;
      display: inline-block;
    }

    .col-form-label {
      text-align: right;
    }

    .figure-img {
      width: 100px;
      height: 100px;
      cursor: pointer;
    }

    #upload {
      display: none;
    }
  </style>
</head>

<body>
  <div class="container">
    <h1 class="p-5">个人设置</h1>
    <form class="col-4">
      <div class="row mb-3">
        <label class="col-form-label col-3">昵称：</label>
        <div class="col-9">
          <input class="form-control col-9" type="text" name="nickname" />
        </div>
      </div>
      <div class="row mb-3">
        <label class="col-form-label col-3">籍贯：</label>
        <div class="col-9">
          <select class="form-select col-4" name="province">
            <option value="">--省--</option>
          </select>
          <select class="form-select col-4" name="city">
            <option value="">--市--</option>
          </select>
          <select class="form-select col-4" name="area">
            <option value="">--区--</option>
          </select>
        </div>
      </div>
      <div class="row mb-3">
        <label class="col-form-label col-3">头像：</label>
        <div class="col-9">
          <input class="form-control col-9" type="hidden" name="avatar" />
          <figure class="figure">
            <input type="file" id="upload" />
            <img src="https://yanxuan-item.nosdn.127.net/12a882699bd531a1bd428bffe1989525.jpg"
              class="figure-img img-fluid rounded" alt="..." />
            <figcaption class="figure-caption">修改头像</figcaption>
          </figure>
        </div>
      </div>
      <div class="row mb-3">
        <label class="col-3"></label>
        <div class="col-9">
          <button class="btn btn-primary">保存</button>
        </div>
      </div>
    </form>
  </div>

  <script src="./lib/bootstrap.min.js"></script>
  <script src="./lib/axios.js"></script>
  <script>
    // 上传头像
    const upload = document.querySelector('#upload')
    const avatar = document.querySelector('.figure img')
    // 昵称
    const nickname = document.querySelector('[name=nickname]')
    // 省市区
    const province = document.querySelector('[name=province]')
    const city = document.querySelector('[name=city]')
    const area = document.querySelector('[name=area]')

    //----配置请求根路径
    axios.defaults.baseURL = 'http://ajax-api.itheima.net'

    //封装函数，渲染数据
    /* -----------------省 下拉框--------------- */
    async function getProvinceData() {
      const {
        data: {
          data: provinceData
        }
      } = await axios.get('/api/province')
      console.log(provinceData);
      const provinceStr = provinceData.map(item => {
        return `<option value="${item}">${item}</option>`
      }).join('')
      province.innerHTML = '<option value="">--省--</option>' + provinceStr
    }

    /* -----------------市 下拉框--------------- */
    async function getCityData(pname) {
      const {
        data: {
          data: cityData
        }
      } = await axios.get('/api/city', {
        params: {
          pname,
        }
      })
      console.log(cityData);
      const cityStr = cityData.map(item => {
        return `<option value="${item}">${item}</option>`
      }).join('')
      city.innerHTML = '<option value="">--市--</option>' + cityStr
    }

    /* -----------------区 下拉框--------------- */
    async function getAreaData(pname, cname) {
      const {
        data: {
          data: areaData
        }
      } = await axios.get('/api/area', {
        params: {
          pname,
          cname
        }
      })
      console.log(areaData);
      const areaStr = areaData.map(item => {
        return `<option value="${item}">${item}</option>`
      }).join('')
      area.innerHTML = '<option value="">--区--</option>' + areaStr
    }

    async function render() {
      await getProvinceData()
      //设置 默认状态显示的 内容
      province.value = '安徽省'

      await getCityData('安徽省')
      //设置 默认状态显示的 内容
      city.value = '合肥市'
      await getAreaData('安徽省', '合肥市')
      //设置 默认状态显示的 内容
      area.value = '蜀山区'
    }
    render()
    //change监听省下拉框的变化，市下拉框相应发生变化
    province.addEventListener('change', async function () {
      //省数据一变化，市就发生变化，发起ajax请求，渲染数据
      await getCityData(province.value)
      //此时区下拉框内容发生变化
      area.innerHTML = '<option value="">--区--</option>'
    })
    //change监听市下拉框的变化，区下拉框相应发生变化
    city.addEventListener('change', async function () {
      //市数据一变化，省就发生变化，发起ajax请求，渲染数据
      await getAreaData(province.value, city.value)
    })

    //文件上传
    avatar.addEventListener('click', function () {
      upload.click()
    })
    //监听头像上传
    upload.addEventListener('change', async function () {
      console.log(this.files[0]);
      if (!this.files[0]) return alert('没有上传文件')
      const fd = new FormData()
      fd.append('avatar', this.files[0])
      const {
        data: {
          data: {
            url
          }
        }
      } = await axios.post('/api/file', fd)
      //显示图片
      avatar.src = url
    })

    //表单提交
    document.querySelector('form').addEventListener('submit', async function (e) {
      e.preventDefault()
      //判断是否有昵称
      if (nickname.value.length === 0) return alert('请输入昵称')
      //发起请求
      const res = await axios.put('/api/settings', {
        nickname: nickname.value.trim(),
        province: province.value,
        city: city.value,
        area: area.value,
        avatar: avatar.src,
      })
      if (res.status !== 200) return alert('信息保存失败')
      alert(res.data.message)
    })
  </script>
</body>

</html>